package com.shujia.day15.homework;

import java.util.*;

/*
    3.      实现List和Map数据的转换。具体要求如下：
    功能1 ：定义方法public void listToMap( ){ }将List中Student元素封装到Map中
    1)    使用构造方法Student(int id,String name,int age,String sex )创建多个学生 信息并加入List
    2)    遍历List ，输出每个Student信息
    3)    将List中数据放入Map ，使用Student的id属性作为key ，使用Student对象 信息作为value
    4)    遍历Map ，输出每个Entry的key和value
    功能2 ：定义方法public void mapToList( ){ }将Map中Student映射信息封装到List
    1)     创建实体类StudentEntry ，可以存储Map中每个Entry的信息
    2)    使用构造方法Student(int id,String name,int age,String sex )创建多个学生 信息，并使用Student的id属性作为key ，存入Map
    3)    创建List对象，每个元素类型是StudentEntry
    4)    将Map中每个Entry信息放入List对象
 */
public class Test2 {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        Student s1 = new Student(1001, "李刚1", 18, "男");
        Student s2 = new Student(1002, "李刚2", 15, "女");
        Student s3 = new Student(1003, "李刚3", 17, "女");
        Student s4 = new Student(1004, "李刚4", 19, "男");
        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);
        for (Student s : list) {
            System.out.println(s);
        }
        System.out.println("--------------------------");
        Map<Integer, Student> map = listToMap(list);
        System.out.println("--------------------------");
        List<StudentEntry> entryList = mapToList(map);
        for (StudentEntry studentEntry : entryList) {
            Map.Entry<Integer, Student> entry = studentEntry.getEntry();
            Integer id = entry.getKey();
            Student s = entry.getValue();
            System.out.println("学号：" + id + ", 详细信息：" + s);
        }

    }


    public static List<StudentEntry> mapToList(Map<Integer, Student> map) {
        ArrayList<StudentEntry> list = new ArrayList<>();

        Set<Map.Entry<Integer, Student>> entries = map.entrySet();
        for (Map.Entry<Integer, Student> entry : entries) {
            StudentEntry studentEntry = new StudentEntry(entry);
            list.add(studentEntry);
        }

        return list;

    }

    public static Map<Integer, Student> listToMap(List<Student> list) {
        HashMap<Integer, Student> map1 = new HashMap<>();

        for (Student s : list) {
            int id = s.getId();
            map1.put(id, s);
        }

        //遍历map集合
        Set<Map.Entry<Integer, Student>> entries = map1.entrySet();
        for (Map.Entry<Integer, Student> entry : entries) {
            Integer id = entry.getKey();
            Student s = entry.getValue();
            System.out.println("学号：" + id + ", 信息：" + s);
        }

        return map1;

    }
}
